import 'package:json_annotation/json_annotation.dart';
import 'package:t3_data_service/biz_data_source/map/address/poi_search/model/poi_model.dart';
import 'package:t3_data_service/config/request/request.dart';
import 'package:t3_data_service/data_provider/map_sctx/t3_map_sctx_provider.dart';
import 'package:t3_foundation/t3_foundation.dart';
import 'package:t3_map/t3_map_plugin/map/core/t3_location.dart';
import 'package:t3_network/t3_network.dart';

part 't3_poi_data_service.g.dart';

class T3POIDataService {
  ///根据坐标经纬度，逆地理
  static Future<POIModel?> getRegeoFromService({required T3LocationCoordinate2D coordinate}) async {

    final request = _RegeoRequest(coordinate: coordinate);

    try {
      final resp = await T3Network().send(request, fromJson: _RegeoTransformModel.fromJson);
      if (resp.isSuccess()) {
        if (resp.succcessValue?.data != null) {
          final value = (resp.succcessValue?.data)!;
          final longitude = value.coord?.lng;
          final latitude = value.coord?.lat;
          if (longitude != null && latitude != null) {
            final poiModel = POIModel(location: LatLng(latitude, longitude));
            poiModel.name = value.saddress;
            poiModel.cityCode = value.cityCode;
            poiModel.city = value.cityName;
            poiModel.adCode = value.adCode;
            poiModel.district = value.adName;
            poiModel.address = value.address;
            final provider = T3MapType.fromJson(value.supplier);
            poiModel.mapType = provider;
            return poiModel;
          } else {
            return null; 
          }
        }
        else {
          return null;
        }
      } else {
        return null;
      }
    } catch (e) {
      return null;  
    }
  }
}

class _RegeoRequest extends T3GisMapApiRequest {
  @override
  String get path => "/notoken/ws/lbs/v2/geocode/regeo";

  T3LocationCoordinate2D coordinate;

  _RegeoRequest({
    required this.coordinate,
  });

  @override
  Map<String, dynamic> toJson() {
    return {
      'coord':{
        'lat': coordinate.latitude,
        'lng': coordinate.longitude
      }
    };
  }
}

@JsonSerializable(createToJson: false)
class _RegeoTransformModel {
  String? adCode;
  String? adName;
  String? address;
  String? cityCode;
  String? cityName;
  String? provinceName;
  String? saddress;
  @JsonKey(fromJson: IntUtils.dynamicToNullInt)
  int? supplier;

  _CoordTransformModel? coord;

  _RegeoTransformModel();

  factory _RegeoTransformModel.fromJson(dynamic json) => _$RegeoTransformModelFromJson(json);
}

@JsonSerializable(createToJson: false)
class _CoordTransformModel {
  @JsonKey(fromJson: DoubleUtils.dynamicToNullDouble)
  double? lat;
  @JsonKey(fromJson: DoubleUtils.dynamicToNullDouble)
  double? lng;
  _CoordTransformModel(this.lat,this.lng);

  factory _CoordTransformModel.fromJson(Map<String, dynamic> json) => _$CoordTransformModelFromJson(json);
}